package cs.asiainfo.config.dao.impl;

import cs.asiainfo.config.dao.CardDao;
import cs.asiainfo.config.entity.CardEntity;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

import java.sql.Date;
import java.util.List;

/**
 * Created by many on 2016/8/9.
 * @author many
 * 会员卡DAO
 */
public class CardDaoImpl implements CardDao {

    private static SessionFactory sessionFactory;
    private static ServiceRegistry serviceRegistry;

    /**
     * 新增会员卡
     */
    public void createCard(CardEntity cardEntity) throws Exception{
        Configuration configuration = new Configuration().configure();
        serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
        sessionFactory = configuration.buildSessionFactory(serviceRegistry);
        Session session = sessionFactory.getCurrentSession();
        session.beginTransaction();

        session.save(cardEntity);
        session.getTransaction().commit();
    }

    /**
     * 查询会员卡信息
     */
    public CardEntity qryCard(String cardType, int memberId) throws Exception{
        Configuration configuration = new Configuration().configure();
        serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
        sessionFactory = configuration.buildSessionFactory(serviceRegistry);
        Session session = sessionFactory.getCurrentSession();

        if (cardType.equals("年卡")){
            cardType = "y";
        }
        else if (cardType.equals("次卡")){
            cardType = "t";
        }
        else{
            cardType = "v";//v表示类型不合法
        }

        session.beginTransaction();

        StringBuilder sql = new StringBuilder("SELECT * FROM CARD WHERE 1 = 1");
        if (cardType != null){
            sql.append(" AND CARD_TYPE = '" + cardType + "'");
        }
        if (memberId != 0){
            sql.append(" AND MEMBER_ID = " + memberId);
        }
        Query query = session.createSQLQuery(sql.toString()).addEntity(CardEntity.class);
        List<CardEntity> result = query.list();

        if (result != null && result.size() > 0){
            return result.get(0);
        }
        else {
            return null;
        }
    }

    /**
     * 更新会员卡信息
     */
    public void updateCard(int cardId) throws Exception{
        return;
    }
}

